import Util from '@/ck/util/util'
import Config from '@/config'

let stageMap = {}
/** 我是未用机制start  */
/**
 * 在侧边栏展示时，如果当前路由 children 属性为空，则删除该路由 改为了删除children属性
 * delete 操作符用于删除对象的某个属性；如果没有指向这个属性的引用，那它最终会被释放。
 * @param {*} arr 路由配置项数据
 */
function IterationDelateMenuChildren(arr){
  if (arr.length){
    for (const i in arr){
      if (arr[i].children && !arr[i].children.length){//有children字段但没写路由
        delete arr[i].children
      }else if (arr[i].children && arr[i].children.length){
        IterationDelateMenuChildren(arr[i].children)
      }
    }
  }
  return arr
}
/**
 * Shaking 掉无限制路由
 * @param {array} stageConfig 路由配置项数据
 * @param {array} permissions 当前登录管理员所拥有的权限集合
 * @param {object} currentUser 当前登录管理员
 * filter 返回所有 有权限的路由
 */
function permissionShaking (stageConfig,permissions, currentUser ){
  const shookConfig = stageConfig.filter(route=>{
    if (Util.hasPermission(permissions,route,currentUser)){//用户有舞台页面权限
      if (route.children && route.children.length){//子页面过滤
        route.children = permissionShaking(route.children,permissions,currentUser)
      }
      return true
    }
    return false
  })
  return IterationDelateMenuChildren(shookConfig)
}
/** 我是未用机制end  */

function IterationMenuChildren (obj,fuc) {
  if (Array.isArray(obj)){
    obj.forEach(item =>{
      fuc(item)
      IterationMenuChildren(item,fuc)
    })
    return
  }
  if (obj && obj.children){
    fuc(obj)
    IterationMenuChildren(obj.children,fuc)
    return
  }
  if (obj.name){
    fuc(obj)
  }
}
//  Shaking 掉菜单
function menusShaking(stageConfig,menus){
  const list ={}
  Util.deepTravel(stageConfig,item=>{
    list[item.mark] = item
  })
  console.log('list',list)
  let shookConfig = Util._cloneDeep(menus)
  IterationMenuChildren(shookConfig, item=>{
    let cell = list[item.Configure]
    if(cell) {
      item.children = item.Children
      item.title = item.JuName
      item.type = cell.type
      item.name = cell.name
      item.path = cell.path
      item.filePath = cell.filePath
      item.inNav = cell.inNav
      item.icon = cell.icon
      item.order = cell.order
    }
    else
    {
      item.inNav = false
    }
  })
   // console.log('shookConfig',JSON.stringify(shookConfig))
  return shookConfig
}
//  过滤配置权限相关
function deepGetSideBar (target, level = 3){
  if (Array.isArray(target)){
    const acc = target.map(item => deepGetSideBar(item, level-1))
    return acc.filter(item => item !==null) //过滤出不符合条件的
  }
  // 检测是否需要在左侧菜单栏中显示
  if (!target.inNav){
    return null
  }
  // 处理 folder 模式
  if (target.type === 'folder' && level !==0){
    const sideConfig = {}
    sideConfig.name = target.name
    sideConfig.title = target.title
    sideConfig.icon = target.icon
    sideConfig.path = target.path || Util.getRandomStr(6)
    sideConfig.children = target.children.map(item => deepGetSideBar(item, level -1))
    sideConfig.children = sideConfig.children.filter(item => item !== null)
    return sideConfig
  }
  // // 处理一级就是 view 的情况
  if (target.type === 'view') {
    const sideConfig = {}
    sideConfig.name = target.name
    sideConfig.title = target.title
    sideConfig.icon = target.icon
    sideConfig.path = target.path
    return sideConfig
  }
  // 处理 appTab 情况
  if (target.type === 'tab'){
    const sideConfig = {}
    sideConfig.name = target.name
    sideConfig.title = target.title
    sideConfig.icon = target.icon
    sideConfig.path = target.path
    // 如果 Tab 没有设置默认打开的路由, 则设置为第一个子节点路由
    if (!sideConfig.path) {
      if (target.children && target.children.length > 0 && target.children[0].path) {
        sideConfig.path = target.children[0].path
      }
    }
    return sideConfig
  }
  // 最后一层, 都当做子节点处理
  if (level <= 0){
    const sideConfig = {}
    sideConfig.name = target.name
    sideConfig.title = target.title
    sideConfig.icon = target.icon
    sideConfig.path = Util.getRandomStr(6)
    return sideConfig
  }

  return null
}
const getters = {
  logined : state => state.logined,
  user: state => state.user,
  stageList: () => stageMap,
  getStageByName: () =>{
    return name => stageMap[name]
  },
  //通过让 getter 返回一个函数，来实现给 getter 传参
  //Object.getOwnPropertySymbols()方法返回一个数组，包含给定对象所有自有的Symbol值的属性（包括不可枚举的Symbol值属性）。
  getStageByRoute: () => (path) => {
    const result = Object.getOwnPropertySymbols(stageMap).find( key => stageMap[key].path === path)
    return stageMap[result]
  },
  //  获取有权限的舞台配置
  permissionStageConfig(state){
    const {stageConfig,permissions,menus,user} = state
    const tempStageConfig = Util._cloneDeep(stageConfig)//深拷贝
    let shookConfig ={}
    if (Config.menus){
       shookConfig = menusShaking(tempStageConfig, menus)
    }else {
       shookConfig = permissionShaking(tempStageConfig, permissions , user)
    }
    const list ={}
    Util.deepTravel(shookConfig, item =>{
      list[item.name] = item
    })
    stageMap = list
    return shookConfig
  },
  //  获取侧边栏配置
  sideBarList(state,getter){
    const { sideBarLevel } = state
    const  {permissionStageConfig} = getter
    const sideBar = deepGetSideBar(permissionStageConfig, sideBarLevel)
    // console.log('我是sidelist=',sideBar)
    return sideBar
  },
  // TODO 还没理解透抽空再看
  getStageInfo(state,getter){
    const {stageConfig} = state
    const  {permissionStageConfig} = getter
    const cache = {}
    function findStage (stages, name) {
      let result
      if (Array.isArray(stages)) {
        for (let i=0; i<stages.length; i+=1){//每一个子项执行自身函数
          result = findStage(stages[i],name)
          if (result){
            break
          }
        }
        return result
      }
      if (stages.children && stages.children.length){ //如果有children子路由
        result = findStage(stages.children, name)
        if (result) {//如果查到子路由数据把父路由unshift到结果集汇总
          result.unshift(stages)
        }
        return result
      }
      if (stages.name === name){ //查找到底层的name相等 返回
        return [stages]
      }
      return false //如果查不到返回false
    }
    return name => {
      if (cache[name]){
        return cache[name]
      }
      const stageInfo = findStage(stageConfig, name)
      if (stageInfo) {
        cache[name] = stageInfo
      }
      return stageInfo
    }
  },
}
export default getters
